package com.foxzzz.flinktest.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: [wujie]
 * @createTime: [2019/12/18 16:43]
 * @description:
 */
public class WordMap extends HashMap<String, Integer> {


    private Integer count = 0;

    public WordMap() {

    }

    public Integer getCount() {
        return count;
    }

    public double incr(String name) {
        count++;
        String[] split = name.split("");
        Double delta = 0D;
        for (String s : split) {
            Integer integer = Optional.ofNullable(get(s)).orElse(0);
            if (integer != 0) {
                delta += Math.log(1 - (integer + 1) / (count * 1.0));
            }
            if (count > 1) {
                delta -= Math.log(1 - integer / (count - 1.0));
            }
            put(s, integer + 1);
        }
        return delta;
    }


    /**
     * 做拉普拉斯光滑
     */
    private Double LaplaceSmooth(String word, Double alpha) {
        if (alpha == null) {
            alpha = 1.0;
        }
        int c = Optional.ofNullable(get(word)).orElse(0);
        int distinctNum = keySet().size();
        return (c + alpha) / (c + distinctNum * alpha);
    }

    //logP(Xi=1|Y)−logP(Xi=0|Y)

    public Double GetLogProb(String word) {
        Double smooth = LaplaceSmooth(word, null);
        return Math.log(smooth) - Math.log(1 - smooth);
    }

    public static void main(String[] args) {
        String path = "D:\\work\\foundation.info.0.log";
        List<Map> list=new LinkedList<>();
        ObjectMapper objectMapper=new ObjectMapper();
        Pattern pattern = Pattern.compile("短信网关参数打印\\{.*\\}");
        try (BufferedReader bf = new BufferedReader(new FileReader(path)); FileWriter fw=new FileWriter("d:\\work\\out.txt")) {
            String line = null;
            while ((line = bf.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    String group = matcher.group();
                    group = group.replaceAll("短信网关参数打印(\\{.*\\})", "$1");
                    Map map = objectMapper.readValue(group, Map.class);
                    list.add(map);
                }

            }

            fw.write(objectMapper.writeValueAsString(list));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
